// src/App.js
import React, { useState, useCallback } from 'react';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { Container, Typography, Box, Alert, Grid } from '@mui/material';
import { FixedSizeGrid } from 'react-window';
import AutoSizer from 'react-virtualized-auto-sizer';
import FolderSelector from './components/FolderSelector';
import ImageItem from './components/ImageItem';
import DragAndDropArea from './components/DragAndDropArea';
import AddTargetDirectoryForm from './components/AddTargetDirectoryForm';
import { traverseDirectory, isSystemDirectory } from './utils/fileUtils';
import CustomDragLayer from './components/CustomDragLayer';

const App = () => {
  const [images, setImages] = useState([]);
  const [sourceDirectory, setSourceDirectory] = useState(null);
  const [errors, setErrors] = useState([]);
  const [targetDirectories, setTargetDirectories] = useState([]);

  // 选择源文件夹后，初始化目标文件夹列表
  const handleFolderSelected = async (directoryHandle) => {
    setSourceDirectory(directoryHandle);
    const imgList = [];
    const encounteredErrors = [];
    const existingTargetDirs = [];

    await traverseDirectory(directoryHandle, (entry) => {
      if (entry.kind === 'file') {
        imgList.push(entry);
      } else if (entry.kind === 'directory') {
        existingTargetDirs.push({
          name: entry.name,
          handle: entry.handle,
        });
      }
    }, (error) => {
      encounteredErrors.push(error);
    });

    setImages(imgList);
    setTargetDirectories(existingTargetDirs);

    if (encounteredErrors.length > 0) {
      setErrors(encounteredErrors);
      alert('部分文件或文件夹无法访问，已跳过这些内容。');
    }
  };

  // 处理文件拖放到指定的目标文件夹
  const handleDrop = async (item, targetDir) => {
    if (!sourceDirectory) {
      alert('请先选择要整理的源文件夹');
      return;
    }

    try {
      const folder = await sourceDirectory.getDirectoryHandle(targetDir.name, { create: true });
      const newFileHandle = await folder.getFileHandle(item.name, { create: true });
      const writable = await newFileHandle.createWritable();
      await writable.write(item.file);
      await writable.close();

      await sourceDirectory.removeEntry(item.name, { recursive: false });

      setImages(prevImages => prevImages.filter((_, index) => index !== item.index));

      setTargetDirectories(prevDirs =>
        prevDirs.map(dir =>
          dir.name === targetDir.name
            ? { ...dir, imageCount: (dir.imageCount || 0) + 1 }
            : dir
        )
      );

    } catch (error) {
      console.error('移动图片失败:', error);
      alert('移动图片时发生错误');
    }
  };
  // 添加新的目标文件夹
  const handleAddTargetDirectory = async (dirName) => {
    if (!dirName.trim()) {
      alert('文件夹名称不能为空');
      return;
    }

    const exists = targetDirectories.some(dir => dir.name === dirName);
    if (exists) {
      alert('文件夹名称已存在');
      return;
    }

    try {
      const folderHandle = await sourceDirectory.getDirectoryHandle(dirName, { create: true });
      setTargetDirectories([...targetDirectories, { name: dirName, handle: folderHandle }]);
    } catch (error) {
      console.error(`创建文件夹 "${dirName}" 失败:`, error);
      alert('创建文件夹时发生错误');
    }
  };

  // 删除目标文件夹
  const handleRemoveTargetDirectory = async (index) => {
    const dirToRemove = targetDirectories[index];
    try {
      const imagesToReturn = [];
      await traverseDirectory(dirToRemove.handle, (entry) => {
        if (entry.kind === 'file') {
          imagesToReturn.push(entry);
        }
      });

      setImages(prevImages => [...prevImages, ...imagesToReturn]);

      const newTargetDirs = [...targetDirectories];
      newTargetDirs.splice(index, 1);
      setTargetDirectories(newTargetDirs);

      alert(`已移除 "${dirToRemove.name}" 文件夹，${imagesToReturn.length} 个文件已返回到所有图片中`);
    } catch (error) {
      console.error(`移除文件夹 "${dirToRemove.name}" 失败:`, error);
      alert('移除文件夹时发生错误');
    }
  };

  const Cell = useCallback(({ columnIndex, rowIndex, style }) => {
    const index = rowIndex * 4 + columnIndex;
    const image = images[index];
    if (!image) return null;
    return (
      <div style={{...style, padding: '5px'}}>
        <ImageItem key={`${image.name}-${index}`} image={image} index={index} />
      </div>
    );
  }, [images]);

  return (
    <DndProvider backend={HTML5Backend}>
      <CustomDragLayer />
      <Container maxWidth="xl" sx={{ padding: '20px', height: '100vh', display: 'flex', flexDirection: 'column' }}>
        <Typography variant="h4" gutterBottom align="center">
          图片分类整理工具
        </Typography>
        <FolderSelector onFolderSelected={handleFolderSelected} />
        {sourceDirectory && (
          <Box mt={4} sx={{ flexGrow: 1, display: 'flex', overflow: 'hidden' }}>
            <Grid container spacing={2}>
              <Grid item xs={12} md={8} sx={{ height: 'calc(100vh - 100px)', overflow: 'auto' }}>
                <Typography variant="h5" gutterBottom>
                  所有图片 ({images.length})
                </Typography>
                <AutoSizer>
                  {({ height, width }) => (
                    <FixedSizeGrid
                      columnCount={5}
                      columnWidth={width / 5}
                      height={height}
                      rowCount={Math.ceil(images.length / 5)}
                      rowHeight={200}
                      width={width}
                    >
                      {Cell}
                    </FixedSizeGrid>
                  )}
                </AutoSizer>
              </Grid>
              <Grid item xs={12} md={4} sx={{ height: 'calc(100vh - 200px)', overflow: 'auto' }}>
                <AddTargetDirectoryForm onAdd={handleAddTargetDirectory} />
                <Grid container spacing={1}>
                  {targetDirectories.map((dir, index) => (
                    <Grid item xs={6} sm={4} md={6} lg={4} key={index}>
                      <Box
                        sx={{
                          border: '1px solid #ccc',
                          borderRadius: '4px',
                          padding: '5px',
                          height: '120px',
                          position: 'relative',
                        }}
                      >
                        <Typography
                          variant="caption"
                          noWrap
                          sx={{
                            position: 'absolute',
                            top: 2,
                            left: 5,
                            right: 5,
                            backgroundColor: 'rgba(255, 255, 255, 0.7)',
                            padding: '2px 4px',
                            borderRadius: '2px',
                            zIndex: 1,
                          }}
                        >
                          {dir.name} ({dir.imageCount || 0})
                        </Typography>
                        <DragAndDropArea onDrop={(item) => handleDrop(item, dir)} />
                        <Typography
                          variant="caption"
                          color="error"
                          sx={{
                            cursor: 'pointer',
                            position: 'absolute',
                            bottom: 2,
                            right: 5,
                            backgroundColor: 'rgba(255, 255, 255, 0.7)',
                            padding: '2px 4px',
                            borderRadius: '2px',
                            zIndex: 1,
                          }}
                          onClick={() => handleRemoveTargetDirectory(index)}
                        >
                          移除
                        </Typography>
                      </Box>
                    </Grid>
                  ))}
                </Grid>
              </Grid>
            </Grid>
          </Box>
        )}
        {errors.length > 0 && (
          <Box mt={4}>
            <Alert severity="error">
              <Typography variant="h6">无法访问以下文件或文件夹：</Typography>
              <ul>
                {errors.map((error, index) => (
                  <li key={index}>{error.message || '未知错误'}</li>
                ))}
              </ul>
            </Alert>
          </Box>
        )}
      </Container>
    </DndProvider>
  );
};

export default App;